package user

import (
	"encoding/json"
	"fmt"
	"forum/app/model/userModel"
	userService "forum/app/service/user"
	userData "forum/app/structData/user"
	"forum/app/tools"
	"net/http"
)

// RegisterRequest 注册请求体
type RegisterRequest struct {
	Username    string `json:"username"`
	Password    string `json:"password"`
	RedPassword string `json:"redPassword"`
}

// LoginRequest 登录请求体
type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// Register 注册接口
func Register(w http.ResponseWriter, r *http.Request) {
	// 从请求中提取用户注册信息
	user := RegisterRequest{
		Username:    r.FormValue("username"),
		Password:    r.FormValue("password"),
		RedPassword: r.FormValue("redPassword"),
	}

	//服务层验证数据
	errorOccurred := false
	tools.TryCatch(func() {
		userService.RegisterService(map[string]interface{}{
			"username":    user.Username,
			"password":    user.Password,
			"redPassword": user.RedPassword,
		})
	}, func(err any) {
		tools.OutPutError(w, fmt.Sprint(err))
		errorOccurred = true
	})
	//捕获到异常 停止运行
	if errorOccurred {
		return
	}

	//创建用户
	createUser := map[string]any{
		"username": user.Username,
		"password": user.Password,
	}
	result := userModel.CreateUser(createUser)
	if result {
		tools.OutPutSuccess(w, "注册成功")
	}
}

// Login 登录接口
func Login(w http.ResponseWriter, r *http.Request) {
	var requestData userData.LoginRequest
	tools.TryCatch(func() {
		userInfo := userService.LoginService(requestData)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"data":   userInfo,
			"status": "success",
			"code":   "200",
		})
	}, func(err any) {
		json.NewEncoder(w).Encode(map[string]interface{}{
			"message": fmt.Sprint(err),
			"status":  "error",
			"code":    "500",
		})
	})
}

// GetUserInfo 获取用户信息
func GetUserInfo(w http.ResponseWriter, r *http.Request) {
	userMap := map[string]interface{}{
		"username": r.FormValue("username"),
	}
	userService.GetUserInfo(userMap)
}

// UpdateUserInfo 修改用户信息
func UpdateUserInfo(w http.ResponseWriter, r *http.Request) {

}

// Logout 登录退出
func Logout(w http.ResponseWriter, r *http.Request) {}

func LevelUp(w http.ResponseWriter, r *http.Request) {}

func OpenMember(w http.ResponseWriter, r *http.Request) {
	memberType := r.FormValue("type")

	switch memberType {
	case "0":
		memberType = ""
		break
	case "1":

	}
}
